package ihm.applet;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Cursor;
import java.io.File;

import ihm.loader.JProgressBarExtended;
import ihm.panel.KrakenTablePanel;
import ihm.panel.TablePanel;
import ihm.panel.camera.CameraPanel;
import ihm.panel.file.LoginPanel;
import ihm.panel.file.WelcomePanel;
import ihm.panel.info.AlertPanel;
import ihm.panel.info.HelpPanel;
import ihm.panel.info.LoggerPanel;
import ihm.panel.admin.AdministrationPanel;

import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;

import org.hibernate.Session;

import bdd.sql.server.bean.User;
import bdd.sql.server.hibernate.HibernateUtil;

import enumTypes.Rank;

/**
 * Kraken Applet.
 * @author Guillaume Pocas & Jean-Fraçois Augé
 */
public class KrakenApplet extends JApplet {

	private static final long serialVersionUID = 1L;
	private JPanel main_jp;
	private JTabbedPane tabbedPane;
	
	//private Session session;
	//private Session externalSession;

	//private User user;
	private int user_ID = 0;
	private boolean userLogged;
	
	//TODO mettre une règle sur les mots de passe ? genre sur le nombre de caractères, majuscule/minuscule, caractère spécial etc ?
	
	private JPanel progress_jp;
	private JPanel login_jp;
	
	private JPanel welcome_jp;
	private JPanel admin_jp;
	private CameraPanel camera_jp;
	private JPanel log_jp;
	//private JPanel param_jp;
	private AlertPanel alert_jp;
	private JPanel help_jp;
	
	@Override
	public void init() {
		super.init();
		
		setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
		System.setSecurityManager(null);
		
		userLogged = false;
		
		try {
			UIManager.setLookAndFeel(new NimbusLookAndFeel());
		} catch (Exception e) {
			e.printStackTrace();
		}

		//session = HibernateUtil.getSession();
		//externalSession = ExternalHibernateUtil.getSession();
		userLogged = false;
		//user = new User();

		try {
			UIManager.setLookAndFeel(new NimbusLookAndFeel());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		setVisible(true);
		new File(System.getProperty("user.home")+"\\kraken").mkdir();
		progress_jp = new JProgressBarExtended();
		add(progress_jp);
		validate();
		((JProgressBarExtended) progress_jp).load();
		
		initPanel();
		setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		
		remove(progress_jp);
		validate();
	}

	/**
	 * Initialisation de l'applet.
	 */
	public void initPanel() {
		main_jp = new JPanel();
		
		
		
		/*
		 * Layout configuration
		 */
		setLayout(new BorderLayout());
		main_jp.setLayout(new CardLayout());
		tabbedPane = new JTabbedPane();
		
		ChangeListener changeListener = new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				JTabbedPane sourceTabbedPane = (JTabbedPane) e.getSource();
		        JPanel pan = (JPanel) sourceTabbedPane.getSelectedComponent();
		        if(pan instanceof CameraPanel) {
		        	if(pan.isShowing()){
			        	CameraPanel panel = (CameraPanel)pan;
			        	panel.getNodePanel().setBuildTree(true);
			        	panel.getNodePanel().createNodes();
			        	panel.getNodePanel().setBuildTree(false);
		        	}
		        }
		        
		        if(pan instanceof TablePanel) {
					if(pan.isShowing()) {
						((TablePanel) pan).updateTableInfo();
						System.out.println("refresh");
					}
				}
		    }
		};
		tabbedPane.addChangeListener(changeListener);
		
		login_jp = new LoginPanel(this);
		welcome_jp = new WelcomePanel(this);
		admin_jp = new AdministrationPanel(this);
		alert_jp = new AlertPanel(this);
		camera_jp = new CameraPanel(this);
		log_jp = new LoggerPanel(this);
		//param_jp = new ParamPanel(this);
		help_jp = new HelpPanel(this);
		
		
		
		main_jp.add(login_jp, "Connexion");
		main_jp.add(tabbedPane, "Onglets");
		add(main_jp, BorderLayout.CENTER);
		
	}
	
	/**
	 * Connecte un utilisateur.
	 * @param id
	 */
	//public void connect(User user) {
	public void connect(int id) {
		//setUser(user);
		setUser_ID(id);
		setUserLogged(true);
		//initTabs(user.getUser_rank());
		initTabs();
		
		this.camera_jp.getNodePanel().setBuildTree(true);
		this.camera_jp.getNodePanel().createNodes();
		this.camera_jp.getNodePanel().setBuildTree(false);
		this.camera_jp.setPanel("Default");
		
		((CardLayout) main_jp.getLayout()).show(main_jp, "Onglets");
	}
	
	/**
	 * Déconnecte un utilisateur.
	 */
	public void disconnect() {
		((CardLayout) main_jp.getLayout()).show(main_jp, "Connexion");
		tabbedPane.removeAll();
		setUserLogged(false);
		//setUser(null);
		setUser_ID(0);
	}
	
	/**
	 * Initialise les onglets en fonction du rang de l'utilisateur.
	 */
	//public void initTabs(Rank rank) {
	public void initTabs() {
		tabbedPane.removeAll();

		Session session = getSession();
		User user = (User) session.load(User.class, getUser_ID());
		
		tabbedPane.addTab("Accueil", welcome_jp);
		if(user.getUser_rank() == Rank.Administrateur)
			tabbedPane.addTab("Administration", admin_jp);
		tabbedPane.addTab("Gestion des caméras", camera_jp);
		tabbedPane.addTab("Alertes", alert_jp);
		tabbedPane.addTab("Historique", log_jp);
		//tabbedPane.addTab("Paramètres", param_jp);
		tabbedPane.addTab("Aide", help_jp);
		
		((HelpPanel) help_jp).initPanel(user.getUser_rank());
		
		session.close();
	}
	
	/**
	 * Set the main panel to the new chosen panel.
	 * @param panelName
	 */
	public void setPanel(String panelName) {
		System.out.println("changing to panel "+panelName);
		for(int i=0; i<tabbedPane.getTabCount(); i++)
			if(tabbedPane.getTitleAt(i).equals(panelName)) {
				tabbedPane.setSelectedIndex(i);
				JPanel panel = (JPanel)tabbedPane.getTabComponentAt(i);
				if(panel instanceof KrakenTablePanel) {
					if(panel.isShowing()) {
						KrakenTablePanel pan = (KrakenTablePanel) panel;
						pan.updateTableInfo();
						pan.getAppletTableModel().setData(pan.getColumnContent());
						pan.getAppletTableModel().fireTableDataChanged();
					}
				}
			}
	}

	public boolean isUserLogged() { return userLogged; }
	public void setUserLogged(boolean userLogged) { this.userLogged = userLogged; }
	
	public Session getSession() { return HibernateUtil.getSession(); }
	//public Session getSession() { return session; }
	//public void setSession(Session session) { this.session = session; }
	
	//public Session getExternalSession() { return externalSession; }
	//public void setExternalSession(Session session) { this.externalSession = session; }

	//public User getUser() { return user; }
	//public void setUser(User user) { this.user = user; }

	public int getUser_ID() { return user_ID; }
	public void setUser_ID(int user_ID) { this.user_ID = user_ID; }
	
}
